package dao

import (
	"errors"
	"github.com/e421083458/gin_scaffold/dto"
	jwt "github.com/e421083458/gin_scaffold/public"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"html"
	"log"
	"strconv"
	"time"
)

type Sort struct {
	Id   int    `json:"id" `
	Name string `json:"name" `
	Pid  string `json:"pid"`
	Icon string `json:"icon"`
}
type Product struct {
	Id          int     `json:"id"`
	Image       string  `json:"image"`
	SliderImage string  `json:"slider_image"`
	StoreName   string  `json:"store_name"`
	StoreInfo   string  `json:"store_info"`
	CateId      int     `json:"cate_id"`
	Price       float64 `json:"price"`
	Postage     float64 `json:"postage"`
	Sales       int     `json:"sales"`
	Stock       int     `json:"stock"`
	IsPostage   int     `json:"is_postage" `
	Uns_id      int     `json:"uns_id"`
	Chengdu     string  `json:"level"`
	Bingzheng   string  `json:"bname"`
}

//我的产品集合
type Products struct {
	Push      *Pulse `json:"push"`
	Interpret string `json:"interpret"`
}
type Order struct {
	Id           int             `json:"id,omitempty"`
	Type         int             `json:"type,omitempty"`
	OrderId      string          `json:"order_id"`
	Uid          int             `json:"uid,omitempty"`
	RealName     string          `json:"real_name,omitempty"`
	UserPhone    string          `json:"user_phone,omitempty"`
	UserAddress  string          `json:"user_address,omitempty"`
	ProductId    int             `json:"product_id,omitempty"`
	FreightPrice decimal.Decimal `json:"freight_price,omitempty"`
	TotalNum     int64           `json:"total_num,omitempty"`
	TotalPrice   decimal.Decimal `json:"total_price,omitempty"`
	PayPrice     decimal.Decimal `json:"pay_price,omitempty"`
	Paid         int             `json:"paid,omitempty"`
	PayTime      int64           `json:"pay_time"`
	AddTime      int64           `json:"add_time,omitempty"`
	Status       int             `json:"status"`
	DeliveryName string          `json:"delivery_name,omitempty"`
	DeliveryCode string          `json:"delivery_code,omitempty"`
	DeliveryId   string          `json:"delivery_id,omitempty"`
	Unique       int64           `json:"unique"`
}

type Order2 struct {
	Id           int             `json:"id,omitempty"`
	Type         int             `json:"type,omitempty"`
	OrderId      string          `json:"order_id"`
	Uid          int             `json:"uid,omitempty"`
	RealName     string          `json:"real_name,omitempty"`
	UserPhone    string          `json:"user_phone,omitempty"`
	UserAddress  string          `json:"user_address,omitempty"`
	ProductId    int             `json:"product_id,omitempty"`
	ProductName  string          `json:"product_name,omitempty"`
	ProductImage string          `json:"product_image,omitempty"`
	FreightPrice decimal.Decimal `json:"freight_price,omitempty"`
	TotalNum     int64           `json:"total_num,omitempty"`
	TotalPrice   decimal.Decimal `json:"total_price,omitempty"`
	PayPrice     decimal.Decimal `json:"pay_price,omitempty"`
	Paid         int             `json:"paid,omitempty"`
	PayTime      int64           `json:"pay_time"`
	AddTime      int64           `json:"add_time,omitempty"`
	Status       int             `json:"status"`
	DeliveryName string          `json:"delivery_name,omitempty"`
	DeliveryCode string          `json:"delivery_code,omitempty"`
	DeliveryId   string          `json:"delivery_id,omitempty"`
	Unique       int64           `json:"unique"`
}

//返佣金日志
type Bonu struct {
	Id          int             `json:"id,omitempty"`
	BelongId    int             `json:"belong_id"`
	SourceId    int             `json:"source_id"`
	Name        string          `json:"name"`
	OrderNo     string          `json:"order_no"`
	ProductName string          `json:"product_name"`
	Price       decimal.Decimal `json:"price"`
	Image       string          `json:"image"`
	Money       decimal.Decimal `json:"money"`
	Content     string          `json:"content"`
	IsType      int             `json:"is_type"`
	Status      int             `json:"status"`

	CreatedAt    time.Time `json:"create_at"`
	UnfreezeTime time.Time `json:"unfreeze_time"`
	DeletedAt    string    `json:"delete_at"`
}

//各级会员返佣金比率
type Rewards struct {
	Id         int     `json:"id,omitempty"`
	GradeId    int     `json:"grade_id"`
	GradeName  string  `json:"grade_name"`
	RewardRate float64 `json:"reard_rate"`
	TopRate    float64 `json:"top_rate"`
}

//症状标签分类-大类结构体
type UBType struct {
	TypeId   int              `json:"id,omitempty"`
	TypeName string           `json:"type_name"`
	Sons     []UserUnscramble `json:"sons"`
}

// 查询分类
func (f *Sort) SelectSort(c *gin.Context, tx *gorm.DB) (error, []Sort) {

	var sort []Sort
	err := tx.Table("hr_wx_product_type").Find(&sort).Error
	if err != nil {
		return err, nil
	}
	return nil, sort
}

// 查询标签分类
func (f *UBType) SelectUns(c *gin.Context, tx *gorm.DB) (error, []UBType) {
	var Lists []UBType
	var re UBType
	var uns []UserUnscramble
	err := tx.Table("hr_wx_user_unscramble").Where("typename=?", "数字脉诊").Find(&uns).Error
	if err != nil {
		return err, nil
	}
	re.TypeId = 1
	re.TypeName = "数字脉诊"
	re.Sons = uns
	Lists = append(Lists, re)
	//体质辨识
	err2 := tx.Table("hr_wx_user_unscramble").Where("typename=?", "体质辨识").Find(&uns).Error
	if err2 != nil {
		return err2, nil
	}
	re.TypeId = 2
	re.TypeName = "中医体质辨识"
	re.Sons = uns
	Lists = append(Lists, re)
	//舌诊
	err3 := tx.Table("hr_wx_user_unscramble").Where("typename=?", "舌诊").Find(&uns).Error
	if err3 != nil {
		return err3, nil
	}
	re.TypeId = 3
	re.TypeName = "舌诊"
	re.Sons = uns
	Lists = append(Lists, re)
	//血压
	err4 := tx.Table("hr_wx_user_unscramble").Where("typename=?", "血压").Find(&uns).Error
	if err4 != nil {
		return err4, nil
	}
	re.TypeId = 4
	re.TypeName = "血压自诊"
	re.Sons = uns
	Lists = append(Lists, re)
	//缺硒
	err5 := tx.Table("hr_wx_user_unscramble").Where("typename=?", "缺硒").Find(&uns).Error
	if err5 != nil {
		return err5, nil
	}
	re.TypeId = 5
	re.TypeName = "缺硒自诊"
	re.Sons = uns
	Lists = append(Lists, re)
	//血糖
	err6 := tx.Table("hr_wx_user_unscramble").Where("typename=?", "血糖").Find(&uns).Error
	if err6 != nil {
		return err3, nil
	}
	re.TypeId = 6
	re.TypeName = "血糖"
	re.Sons = uns
	Lists = append(Lists, re)
	//眼科
	err7 := tx.Table("hr_wx_user_unscramble").Where("typename=?", "眼科").Find(&uns).Error
	if err7 != nil {
		return err7, nil
	}
	re.TypeId = 7
	re.TypeName = "眼疾自诊"
	re.Sons = uns
	Lists = append(Lists, re)
	//背诊
	err8 := tx.Table("hr_wx_user_unscramble").Where("typename=?", "背诊").Find(&uns).Error
	if err8 != nil {
		return err8, nil
	}
	re.TypeId = 8
	re.TypeName = "背诊"
	re.Sons = uns
	Lists = append(Lists, re)
	return nil, Lists
}

//根据用户id查找分润列表
func (f *Bonu) SelectBonus(c *gin.Context, tx *gorm.DB) (error, []Bonu) {

	token := c.Request.Header.Get("token") //从headers获取token
	claims, err := jwt.ParseToken(token)
	if err != nil {
		return err, nil
	}
	log.Println(+claims.Uid)
	var bonus []Bonu
	errs := tx.Debug().Table("hr_bonu").Joins("left join hr_wx_uorder ord on hr_bonu.order_no=ord.order_id").Joins("left join hr_wx_product p on ord.product_id=p.id").
		Select("hr_bonu.*,p.store_name product_name,p.price,p.image").Where("belong_id=? and is_type=1", claims.Uid).Find(&bonus).Error //, claims.Uid
	log.Println(bonus)
	for j := 0; j < len(bonus); j++ {
		// 时间字符串
		//t, _ := time.Parse("2006-01-02 15:04:05", bonus[j].CreatedAt.String())
		//timest := t.Unix()
		//res_t := timest + 86400*30
		//timestamp := int64(res_t) // 时间戳，单位为秒
		//t1 := time.Unix(timestamp, 0)
		log.Println("-----------")
		log.Println(time.Now().AddDate(0, 0, 15))
		//log.Println("-----------")
		bonus[j].UnfreezeTime = bonus[j].CreatedAt.AddDate(0, 0, 15) //.Format("2006-01-02 15:04:05")
		//t := time.Now()

		//log.Println("-----------")
		//log.Println(formattedTime)
		//bonus[j].UnfreezeTime = formattedTime
	}
	// 将时间字符串解析为时间对象
	//t, err := time.Parse("2006-01-02 15:04:05", v.CreatedAt.String())
	//if err != nil {
	//	fmt.Println("时间解析错误：", err)
	//}

	if errs != nil {
		return errs, nil
	}
	return nil, bonus
}

// 查询产品
func (f *Product) SelectProduct(c *gin.Context, tx *gorm.DB, UnsId string) (error, []Product) { //

	var product []Product
	//err := tx.Table("hr_wx_product").Where("is_show=? and uns_id!=0 and slider_image!=''", 1).Find(&product).Error
	//if err != nil {
	//	return err, nil
	//}//
	if UnsId != "" {
		err := tx.Table("hr_wx_product").Where("is_show=? and uns_id=? and slider_image!=''", 1, UnsId).Find(&product).Error
		log.Println("记录标记0-----")
		if err != nil {
			return err, nil
		}
	} else {
		token := c.Request.Header.Get("token") //从headers获取token，进而获取用户id
		claims, err := jwt.ParseToken(token)
		log.Println(+claims.Uid)
		////cons01 := &Analysis{}
		//var cons01 []Analysis
		//err01 := tx.Table("hr_wx_cons").Where("uid = ? and type =?", claims.Uid, "1").Order("id desc").Find(&cons01).Error
		//if err01 != nil {
		//	return err01, nil
		//}
		//if cons01 != nil {
		//	log.Println("cons01--")
		//	//cons01的第一行
		//	//cons0101 := cons01[0]
		//	//log.Println(cons0101)
		//}
		////cons03 := &Analysis{}
		//var cons03 []Analysis
		//err03 := tx.Table("hr_wx_cons").Where("uid = ? and type =?", claims.Uid, "3").Order("id desc").Find(&cons03).Error
		//if err03 != nil {
		//	return err03, nil
		//}
		////cons03的长度
		//if cons03 != nil {
		//	//log.Println("cons03--")
		//	//获取cons03的第一条
		//	//cons0301 := cons03[0]
		//	//log.Println(cons0301)
		//}
		err, pulsh := (&Pulse{}).UserPaulseOne(c, tx, claims.Uid) //
		if err != nil {
			//return err, nil
		}
		if pulsh.Id > 0 {
			//五脏查询
			log.Println("记录标记11-----")
			err, wz := (&UserWuzhang{}).Wuzhang(c, tx, pulsh.Id)
			var DbLists []DbList
			var Db DbList

			Db.Level = wz[0].Heartstatus
			Db.Name = wz[0].Heartname
			DbLists = append(DbLists, Db)
			Db.Level = wz[0].Algorithmstatus
			Db.Name = wz[0].Algorithmname
			DbLists = append(DbLists, Db)
			Db.Level = wz[0].Spleenstatus
			Db.Name = wz[0].Spleenname
			DbLists = append(DbLists, Db)
			Db.Level = wz[0].Lungstatus
			Db.Name = wz[0].Lungsname
			DbLists = append(DbLists, Db)
			Db.Level = wz[0].Renalstatus
			Db.Name = wz[0].Renalname
			DbLists = append(DbLists, Db)
			bingList := []string{"严重", "重度", "中度"}
			level := ""
			name := ""
			for _, vv := range bingList {
				if len(name) > 0 {
					break
				}
				for _, v := range DbLists {
					if vv == v.Level {
						level = v.Level
						name = v.Name
						break
					}
				}
			}
			//五脏程度查询
			log.Println(level)
			_, ress := (&UserUnscramble{}).ChengduFind(c, tx, name, level)
			//log.Println(ress.Id)
			var products1 []Product
			if ress != nil {
				_, products1 = (&Product{}).FindProductsByU(c, tx, ress.Id)
				for _, v := range products1 {
					product = append(product, v)
				}
			}
			//六腑查询
			err, liuf := (&UserLiufu{}).Liufu(c, tx, pulsh.Id)
			log.Println("六腑")
			//log.Println(liuf)
			var DbLists2 []DbList
			var Db2 DbList

			Db2.Level = liuf[0].Gallstatus
			Db2.Name = liuf[0].Gallname
			DbLists2 = append(DbLists2, Db2)
			Db2.Level = liuf[0].Stomachstatus
			Db2.Name = liuf[0].Stomachname
			DbLists2 = append(DbLists2, Db2)
			Db2.Level = liuf[0].Smallstatus
			Db2.Name = liuf[0].Smallname
			DbLists2 = append(DbLists2, Db2)
			Db2.Level = liuf[0].Largestatus
			Db2.Name = liuf[0].Largename
			DbLists2 = append(DbLists2, Db2)
			Db2.Level = liuf[0].Bladderstatus
			Db2.Name = liuf[0].Bladdername
			DbLists2 = append(DbLists2, Db2)
			bingList2 := []string{"严重", "重度", "中度"}
			level2 := ""
			name2 := ""
			for _, vv := range bingList2 {
				if len(name2) > 0 {
					break
				}
				for _, v := range DbLists2 {
					if vv == v.Level {
						level2 = v.Level
						name2 = v.Name
						break
					}
				}
			}
			//六腑程度查询
			log.Println(level2)
			_, ress2 := (&UserUnscramble{}).ChengduFind(c, tx, name2, level2)
			//log.Println(ress2.Id)
			var products2 []Product
			if ress2 != nil {
				_, products2 = (&Product{}).FindProductsByU(c, tx, ress2.Id)
				for _, v := range products2 {
					product = append(product, v)
				}
			}
			//大病查询
			err, dabing := (&Dabing{}).DabingFind(c, tx, pulsh.Id)
			log.Println("大病")
			log.Println(dabing)
			if err != nil {
				return err, nil
			}
			var DbLists3 []DbList
			var Db3 DbList

			Db3.Level = dabing[0].Apoplexy
			Db3.Name = "中风预警"
			DbLists3 = append(DbLists3, Db3)
			Db3.Level = dabing[0].Heart
			Db3.Name = "心脏病预警"
			DbLists3 = append(DbLists3, Db3)
			Db3.Level = dabing[0].Tumour
			Db3.Name = "肿瘤预警"
			DbLists3 = append(DbLists3, Db3)
			bingList3 := []string{"严重", "重度", "中度"}
			level3 := ""
			name3 := ""
			for _, vv := range bingList3 {
				if len(name3) > 0 {
					break
				}
				for _, v := range DbLists3 {
					if vv == v.Level {
						level3 = v.Level
						name3 = v.Name
						break
					}
				}
			}
			//大病程度查询
			log.Println(level2)
			_, ress3 := (&UserUnscramble{}).ChengduFind(c, tx, name3, level3)
			//log.Println(ress3.Id)
			var products3 []Product
			if ress3 != nil {
				_, products3 = (&Product{}).FindProductsByU(c, tx, ress3.Id)
				for _, v := range products3 {
					product = append(product, v)
				}
			}
			//体质查询
			err, tizhi := (&Tizhi{}).TizhiFind(c, tx, pulsh.Id)
			log.Println("体质")
			//log.Println(tizhi)
			if err != nil {
				return err, nil
			}
			var DbLists4 []DbList
			var Db4 DbList
			level4 := ""
			name4 := ""
			if tizhi != nil {
				Db4.Level = tizhi[0].Constitution
				Db4.Name = tizhi[0].Constitutioname
				DbLists4 = append(DbLists4, Db4)
				bingList4 := []string{"严重", "重度", "中度", "轻度"}

				for _, vv := range bingList4 {
					if len(name4) > 0 {
						break
					}
					for _, v := range DbLists4 {
						if vv == v.Level {
							level4 = v.Level
							name4 = v.Name
							break
						}
					}
				}
			}

			//体质程度查询
			log.Println(level4)
			_, ress4 := (&UserUnscramble{}).ChengduFind(c, tx, name4, level4)
			//log.Println(ress4.Id)
			var products4 []Product
			if ress4 != nil {
				_, products4 = (&Product{}).FindProductsByU(c, tx, ress4.Id)
				for _, v := range products4 {
					product = append(product, v)
				}
			}
		}
		//所有产品
		var products []Product
		errs := tx.Table("hr_wx_product").Where("is_show=? and uns_id!=0 and slider_image!=''", 1).Find(&products).Error
		if err != nil {
			return errs, nil
		}
		//判断,产品为空的时候，返回所有产品，不为空时，将其他产品放在下边
		if len(product) == 0 {
			log.Println("记录标记1-----")
			if len(products) > 0 { //所有产品
				for _, v := range products {
					product = append(product, v)
				}
			}

		} else {
			//定义一个内容为数字的不定长度数组
			//ength := len(product)
			log.Println("记录标记2-----")
			var arr [1000]int
			for _, v := range product {
				//将v.Id压入数组arr
				arr[v.Id] = v.Id
			}
			for _, vv := range products {
				//判断vv.Id是否在数组arr中，不存在则压入产品中
				if arr[vv.Id] == 0 {
					product = append(product, vv)
				}
			}
		}

	}

	return nil, product
}

// 查询产品详情
func (f *Product) FindProduct(c *gin.Context, tx *gorm.DB) (error, *Product) {

	product := &Product{}
	err := tx.Table("hr_wx_product").Find(&product).Error
	if err != nil {
		return err, nil
	}
	return nil, product
}
func (f *Product) FindProduct2(c *gin.Context, tx *gorm.DB, id string) (error, *Product) {

	log.Println(id)
	product := &Product{}
	err := tx.Debug().Table("hr_wx_product").Where("id=?", id).Find(&product).Error
	if err != nil {
		return err, nil
	}
	product.StoreInfo = html.UnescapeString(product.StoreInfo)
	return nil, product
}

//根据程度id查找产品
func (f *Product) FindProductByC(c *gin.Context, tx *gorm.DB, uns_id int) (error, *Product) {

	log.Println(uns_id)
	products := &Product{}
	err := tx.Debug().Table("hr_wx_product").Where("uns_id=?", uns_id).Find(&products).Error
	if err != nil {
		return err, nil
	}
	return nil, products
}

//根据程度id查找产品
func (f *Product) FindProductsByU(c *gin.Context, tx *gorm.DB, uns_id int) (error, []Product) {

	log.Println(uns_id)
	var products []Product
	err := tx.Debug().Table("hr_wx_product").Where("uns_id=?", uns_id).Find(&products).Error
	if err != nil {
		return err, nil
	}
	return nil, products
}

// 创建订单
func (f *Order) CreateOrder(c *gin.Context, tx *gorm.DB, params *dto.Order) (error, string) {
	productId := params.ProductId
	if productId > 0 {
		log.Println(params.ProductId)
		err, product := (&Product{}).FindProduct2(c, tx, strconv.Itoa(params.ProductId))
		log.Println(product)
		if err != nil {
			return err, ""
		}
		decimal.DivisionPrecision = 2
		token := c.Request.Header.Get("token") //从headers获取token
		claims, err := jwt.ParseToken(token)
		//获取收货信息
		err, infoAdr := (&Address{}).AddressInfo(c, tx)
		order := &Order{
			Type:         params.Type,
			OrderId:      jwt.Generate(time.Now()),
			Uid:          claims.Uid,
			RealName:     infoAdr.Username,
			UserPhone:    infoAdr.Tel,
			UserAddress:  infoAdr.Province + infoAdr.City + infoAdr.County + infoAdr.Detail,
			ProductId:    params.ProductId,
			FreightPrice: decimal.NewFromFloat(product.Postage).Mul(decimal.NewFromFloat(float64(params.TotalNum))),
			TotalNum:     int64(params.TotalNum),
			TotalPrice:   decimal.NewFromFloat(product.Price).Mul(decimal.NewFromFloat(float64(params.TotalNum))),
			PayPrice:     decimal.NewFromFloat(product.Price + product.Postage).Mul(decimal.NewFromFloat(float64(params.TotalNum))),
			AddTime:      time.Now().Unix(),
			Unique:       time.Now().UnixNano(),
			Status:       -3,
		}
		//fmt.Println(order)
		err = tx.Table("hr_wx_uorder").Create(&order).Error
		if err != nil {
			return err, ""
		}
		return nil, order.OrderId
	} else {
		err, product := (&Product{}).FindProduct2(c, tx, strconv.Itoa(1))
		log.Println(product)
		decimal.DivisionPrecision = 2
		order := &Order{
			Type:         params.Type,
			OrderId:      jwt.Generate(time.Now()),
			Uid:          params.Uid,
			RealName:     params.RealName,
			UserPhone:    params.UserPhone,
			UserAddress:  params.UserAddress,
			ProductId:    params.ProductId,
			FreightPrice: decimal.NewFromFloat(0.0),
			TotalNum:     int64(params.TotalNum),
			TotalPrice:   decimal.NewFromFloat(365.0),
			PayPrice:     decimal.NewFromFloat(365.0),
			AddTime:      time.Now().Unix(),
			Unique:       time.Now().UnixNano(),
			Status:       -3,
		}
		//fmt.Println(order)
		err = tx.Table("hr_wx_uorder").Create(&order).Error
		if err != nil {
			return err, ""
		}
		return nil, order.OrderId
	}

}

// 查询订单
func (f *Order) SelectOrder(c *gin.Context, tx *gorm.DB, uid int, status int) (error, []Order2) {
	//Status都是0啊？

	var order []Order2
	paid := 0 //支付状态
	//db.Joins("left join hr_wx_user fu on hr_wx_user.fromuid=fu.id").Joins("left join hr_wx_user pu on hr_wx_user.from_level_id=pu.id").Order("hr_wx_user.id desc").Select("hr_wx_user.*,fu.truename fname,pu.truename pname").Limit(limit).Offset(offset).Find(&memss).Error
	if status != 0 {
		if status == -3 { //未付款
			status = -3
			paid = 0
		}
		if status == 1 { //待发货
			status = 0
			paid = 1
		}
		if status == 2 { //已收货
			status = 2
			paid = 1
		}
		if status == 4 { //已过期
			status = 4
			paid = 1
		}
		err := tx.Table("hr_wx_uorder").Joins("left join hr_wx_product p on hr_wx_uorder.product_id=p.id").Select("hr_wx_uorder.*,p.store_name product_name,p.image product_image").Where("uid=? and paid=? and status=?", uid, paid, status).Find(&order).Error
		if err != nil {
			return err, nil
		}
	} else {
		err := tx.Table("hr_wx_uorder").Joins("left join hr_wx_product p on hr_wx_uorder.product_id=p.id").Select("hr_wx_uorder.*,p.store_name product_name,p.image product_image").Where("uid=?", uid).Find(&order).Error
		if err != nil {
			return err, nil
		}
	}
	for _, v := range order {
		log.Println(v.Status)
	}

	return nil, order
}

//根据订单id查询信息
func (f *Order) OrderInfo(c *gin.Context, tx *gorm.DB, order_id string) (error, *Order2) {
	order := &Order2{}
	err := tx.Debug().Table("hr_wx_uorder").Joins("left join hr_wx_product p on hr_wx_uorder.product_id=p.id").Select("hr_wx_uorder.*,p.store_name product_name,p.image product_image").Where("order_id=?", order_id).First(&order).Error
	if err != nil {
		return err, nil
	}
	return nil, order
}

func FindUserLevel(c *gin.Context, tx *gorm.DB, uid int) (error, int) {
	err, user := (&Uuser{}).FindUser(c, tx, uid)
	if err != nil {
		return err, 0
	}
	if user.Level == 0 && user.Fromuid != 0 {
		return FindUserLevel(c, tx, user.Fromuid)
	} else if user.Level == 0 && user.Fromuid == 0 {
		return err, 0
	} else if user.Level > 0 {
		return err, user.Id
	} else {
		return err, 0
	}
	return err, 0
}

type Level struct {
	Id    int    `json:"id"`
	Name  string `json:"name"`
	Money int    `json:"money"`
}

func EveryLevel(c *gin.Context, tx *gorm.DB, uid int, orderMoney decimal.Decimal, sid int, orderId string) string {
	log.Println(orderMoney)
	_, user := (&Uuser{}).FindUser(c, tx, uid)
	if user.Level != 0 && user.FromLevelId > 0 {
		//分配自己的利润 money=利润
		var level Level
		tx.Table("hr_wx_user_level").Where("id=?", user.Level).First(&level)
		userOneNewMoney1 := orderMoney
		userOneNewMoney2 := decimal.NewFromFloat(float64(level.Money))
		userOneNewMoney3 := decimal.NewFromFloat(0.01)
		//奖金
		money := userOneNewMoney1.Mul(userOneNewMoney2).Mul(userOneNewMoney3)
		UserOneUpdate := Uuser{BrokerageMoney: user.BrokerageMoney.Add(money)}
		tx.Table("hr_wx_user").Where("id=?", user.Id).Update(&UserOneUpdate)
		add := Bonu{
			BelongId:     user.Id,
			SourceId:     sid,
			Name:         "推荐返佣奖励",
			OrderNo:      orderId,
			Money:        money,
			Content:      "返佣奖励",
			IsType:       1,
			Status:       0,
			UnfreezeTime: time.Now().AddDate(0, 0, 15),
			CreatedAt:    time.Now(),
		}
		tx.Table("hr_bonu").Create(&add)
		return EveryLevel(c, tx, user.FromLevelId, orderMoney, sid, orderId)
	} else if user.Level != 0 && user.FromLevelId == 0 {
		//分配自己的利润 money=利润
		var level Level
		tx.Table("hr_wx_user_level").Where("id=?", user.Level).First(&level)
		userOneNewMoney1 := orderMoney
		userOneNewMoney2 := decimal.NewFromFloat(float64(level.Money))
		userOneNewMoney3 := decimal.NewFromFloat(0.01)
		//奖金
		money := userOneNewMoney1.Mul(userOneNewMoney2).Mul(userOneNewMoney3)
		UserOneUpdate := Uuser{BrokerageMoney: user.BrokerageMoney.Add(money)}
		tx.Table("hr_wx_user").Where("id=?", user.Id).Update(&UserOneUpdate)
		add := Bonu{
			BelongId:     user.Id,
			SourceId:     sid,
			Name:         "推荐返佣奖励",
			OrderNo:      orderId,
			Money:        money,
			Content:      "返佣奖励",
			IsType:       1,
			Status:       0,
			UnfreezeTime: time.Now().AddDate(0, 0, 15),
			CreatedAt:    time.Now(),
		}
		tx.Table("hr_bonu").Create(&add)
		return "完成"
	} else {
		return ""
	}
	return ""
}

func GEtLevel(c *gin.Context, tx *gorm.DB, uid int) int {
	log.Println(uid)
	_, user := (&Uuser{}).FindUser(c, tx, uid)
	//判断user不为空
	if user != nil {
		log.Println(user.Level)
		if user.Level == 0 {
			return GEtLevel(c, tx, user.Fromuid)
		} else {
			return user.Id
		}
	}
	return 0
}

// 订单状态更新 收货
func (f *Order) OrfSave(c *gin.Context, tx *gorm.DB, orderId string, state int) (error, string) {

	orderUp := Order{Status: state}
	//查询订单状态
	var orderInfo Order
	tx.Table("hr_wx_uorder").Where("order_id=?", orderId).First(&orderInfo)
	//处理gorm里面int为空或者0
	//var num int = 2 // 创建一个整数变量 num，并赋值为 42
	//var ptr *int    // 定义一个 *int 类型的指针变量 ptr
	//ptr = &num
	if orderInfo.Status == 0 {
		return errors.New("订单还未发货"), ""
	}
	if orderInfo.Status == 2 {
		return errors.New("订单已收货"), ""
	}
	//校验会员是否是本人 todo

	//更新订单状态
	err := tx.Table("hr_wx_uorder").Where("order_id=?", orderId).Update(&orderUp).Error
	if err != nil {
		return err, ""
	}

	if err != nil {
		return err, ""
	} else {

		if state == 2 { //确认收货，冻结的分佣信息更新解冻时间
			var bonus []Bonu
			if err := tx.Debug().Where("order_no=? and is_type=1", orderId).Find(&bonus).Error; err == nil {
				return err, ""
			}
			//更新佣金解冻时间
			if len(bonus) > 0 {
				for j := 0; j < len(bonus); j++ {
					UnfTime := time.Now().AddDate(0, 0, 7)
					OneUpdate := Bonu{UnfreezeTime: UnfTime}
					tx.Table("hr_wx_user").Where("id=?", bonus[j].Id).Update(&OneUpdate)
				}
			}
		}
	}
	return nil, string(orderUp.Id)
}

// 订单状态更新 支付成功
func (f *Order) OrpSave(c *gin.Context, tx *gorm.DB, orderId string, state int) (error, string) {

	payTime := time.Now().Unix()
	orderUp := Order{Paid: 1, Status: state, PayTime: payTime} //更新支付状态、订单状态和时间
	//查询订单状态
	var orderInfo Order
	tx.Table("hr_wx_uorder").Where("order_id=?", orderId).First(&orderInfo)
	if orderInfo.Status == 1 {
		return errors.New("订单已发货"), ""
	}
	if orderInfo.Status == 2 {
		return errors.New("订单已收货"), ""
	}
	//校验会员是否是本人 todo

	//更新订单状态
	err := tx.Table("hr_wx_uorder").Where("order_id=?", orderId).Update(&orderUp).Error
	if err != nil {
		return err, ""
	}
	err, order := (&Order{}).OrderInfo(c, tx, orderId)

	if err != nil {
		return err, ""
	} else {
		err, user := (&Uuser{}).FindUser(c, tx, order.Uid)
		if err != nil {
			return err, ""
		} else {
			//先判断充值会员,判断产品续费会员产品的话
			if order.ProductId == 12 {
				now := user.Endtime + order.TotalNum*86400*30
				err = tx.Debug().Table("hr_wx_user").Where("id = ?", user.Id).Update("Endtime", now).Error
				log.Println(orderId + "订单续费成功" + string(order.TotalNum) + "个月")
			}

			//递归查询上一级带等级的 传入上一级id
			if user.Fromuid != 0 {
				if state == 0 { //支付完成时候，待发货状态
					err, lastId := FindUserLevel(c, tx, user.Fromuid)
					log.Println(lastId)
					if err != nil {
						return err, ""
					}
					//没有利润
					if lastId == 0 {
						return nil, "success"
					}
					//利润分配
					err, userOne := (&Uuser{}).FindUser(c, tx, lastId)
					log.Println(userOne.Id)
					//查询等级佣金百分比
					//直属上级佣金比例
					var levelList []Level
					tx.Table("hr_wx_user_level").Where("id<=?", userOne.Level).Find(&levelList)
					var oneUserMoney int
					for _, v := range levelList {
						oneUserMoney = oneUserMoney + v.Money
					}
					userOneNewMoney1 := order.PayPrice
					userOneNewMoney2 := decimal.NewFromFloat(float64(oneUserMoney))

					userOneNewMoney3 := decimal.NewFromFloat(0.01)
					money := userOneNewMoney1.Mul(userOneNewMoney2).Mul(userOneNewMoney3)
					UserOneUpdate := Uuser{BrokerageMoney: userOne.BrokerageMoney.Add(money)}
					tx.Table("hr_wx_user").Where("id=?", userOne.Id).Update(&UserOneUpdate)
					add := Bonu{
						BelongId:     userOne.Id,
						SourceId:     order.Uid,
						Name:         "推荐返佣奖励",
						OrderNo:      order.OrderId,
						Money:        money,
						Content:      "返佣奖励",
						IsType:       1,
						Status:       0,
						UnfreezeTime: time.Now().AddDate(0, 0, 15),
						CreatedAt:    time.Now(),
					} //
					tx.Table("hr_bonu").Create(&add)
					//除直接上级其他等级分配 动态分配函数 异步执行分配
					go EveryLevel(c, tx, userOne.FromLevelId, order.PayPrice, order.Uid, order.OrderId)
				}

			}

		}
	}
	return nil, string(orderUp.Id)
}
